package org.jeecg.modules.xj.h5.controller;


import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;

public class WeChatUtil {
    /**
     * 请求微信接口服务，获取小程序全局唯一后台接口调用凭据（access_token）
     * https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/access-token/auth.getAccessToken.html
     *
     * @param appid
     * @param secretKey
     * @return
     */
  /*  public static JSONObject getAccessToken(String appid, String secretKey) {
        String result = null;
        try {
            String baseUrl = "https://api.weixin.qq.com/cgi-bin/token";
            HashMap<String, Object> requestParam = new HashMap<>();
            // 小程序 appId
            requestParam.put("grant_type", "client_credential");
            // 小程序唯一凭证id appid:(换成自己的)
            requestParam.put("appid", appid);
            // 小程序 appSecret（小程序的唯一凭证密钥,换成自己的）
            requestParam.put("secret", secretKey);
            // 发送GET请求读取调用微信接口获取openid用户唯一标识
            result = HttpUtil.get(baseUrl, requestParam);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSONUtil.parseObj(result);
    }*/

    /**
     * 请求微信接口服务，用code换取用户手机号（每个code只能使用一次，code的有效期为5min）
     * https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/phonenumber/phonenumber.getPhoneNumber.html
     *

     * @return
     */
  /*  public static JSONObject getPhoneNumber(String code, String accessToken) {
        String result = null;
        try {
            // 接口调用凭证：accessToken
            String baseUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken;
            HashMap<String, Object> requestParam = new HashMap<>();
            // 手机号调用凭证
            requestParam.put("code", code);
            // 发送post请求读取调用微信接口获取openid用户唯一标识
            String jsonStr = JSONUtil.toJsonStr(requestParam);
            HttpResponse response = HttpRequest.post(baseUrl)
                    .header(Header.CONTENT_ENCODING, "UTF-8")
                    // 发送json数据需要设置contentType
                    .header(Header.CONTENT_TYPE, "application/x-www-form-urlencoded")
                    .body(jsonStr)
                    .execute();
            if (response.getStatus() == HttpStatus.HTTP_OK) {
                result = response.body();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSONUtil.parseObj(result);
    }

    public static void main(String[] args) {
        // 1.请求微信接口服务，获取accessToken
        JSONObject accessTokenJson = WeChatUtil.getAccessToken(weChatPhone.getAppid(), weChatPhone.getSecretKey());
        String accessToken = accessTokenJson.get("access_token", String.class);
        // 2.请求微信接口服务，获取用户手机号信息
        JSONObject phoneNumberJson = WeChatUtil.getPhoneNumber(weChatPhone.getCode(), accessToken);
        WeChatPhoneInfo phoneInfo = phoneNumberJson.get("phone_info", WeChatPhoneInfo.class);
        return phoneInfo.getPurePhoneNumber();
    }*/
    public static void main(String[] args) throws Exception {
        JSONObject wxJson;
        // 获取token
        String token_url = null;

        /**
         * appid切换
         */

            token_url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s",
                    "wx5c172d18bc021d4f", "1ecaab8de2218a808018b264736fba49");



        try {
            JSONObject token = JSON.parseObject(HttpClientSslUtils.doGet(token_url));
            if (token == null) {
//                log.info("获取token失败");
//                return null;
            }
            String accessToken = token.getString("access_token");
            if (StringUtils.isEmpty(accessToken)) {
//                log.info("获取token失败");
     ;
            }
            //获取phone
            String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber"
                    + "?access_token=" + accessToken;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", "146c065de29dcf8f6b5f1cd0589fa33dbbfa75e8f828ba8ebddaf5767745ba59");
            String reqJsonStr = JsonUtil.objToString(jsonObject);
            wxJson = JSON.parseObject(HttpClientSslUtils.doPost(url, reqJsonStr));

            if (wxJson == null) {
//                log.info("获取手机号失败");
//                return ResultResponse.error("获取手机号失败!");
            }
//            return ResultResponse.ok("获取成功!").setData(wxJson);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}